var express = require('express');
// 导入moment
const moment = require('moment')
const AccountModel = require('../../models/AccountModel')
// // 测试
// console.log(moment('2025-02-26').toDate());
// console.log(moment(new Date()).format('YYYY-MM-DD'));

const checkLoginMiddleware = require('../../middlewares/checkLoginMiddleware')

var router = express.Router();

router.get('/', (req, res, next) => {
  res.redirect('/account')
})

// 获取账单明细
router.get('/account', checkLoginMiddleware, (req, res, next) => {
  
  AccountModel.find().sort({time: -1}).then(data => {
    // console.log(data);
    res.render('list', {data, moment})
  }).catch(err => {
    res.status(500).send('获取失败')
  })
  
})

// 添加账单
router.get('/account/create', checkLoginMiddleware, (req, res, next) => {
  res.render('create')
})

// 提交账单
router.post('/account', checkLoginMiddleware, (req, res, next) => {
  console.log(req.body);
  AccountModel.create({
    ...req.body,
    time: moment(req.body.time).toDate()
  }).then(data => {
    console.log(data, '提交成功');
  }).catch(err => {
    res.status(500).send('提交失败')
  })
  res.render('success', {msg: '添加成功了', url: '/account'})
})

// 删除账单
router.get('/account/:id',checkLoginMiddleware, (req, res, next) => {
  console.log(req.params.id);
  AccountModel.deleteOne({_id: req.params.id}).then(data => {
    console.log(data, '删除成功');
  }).catch(err => {
    res.status(500).send('删除失败')
  })
  res.render('success', {msg: '删除成功了', url: '/account'})
})



module.exports = router;
